package org.jeecg.modules.pucheng.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.pucheng.controller.HeZhangController;
import org.jeecg.modules.pucheng.entity.PatrolRecord;
import org.jeecg.modules.pucheng.service.IPatrolRecordService;
import org.jeecg.modules.pucheng.vo.PatrolRecordVo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Slf4j
public class PatrolRecordJob implements Job {
    @Autowired
    private IPatrolRecordService patrolRecordService;
    @Autowired
    private HeZhangController heZhangController;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info(String.format("  更新巡河次数  定时任务 PatrolRecordJob !  时间:" + DateUtils.getTimestamp()));
        List<PatrolRecord> patrolRecords = patrolRecordService.list();
        boolean reflush = false;
        if (patrolRecords.size()!=0){
            PatrolRecord record = patrolRecords.get(0);
            if (record.getCreateTime() == null || record.getUpdateTime() == null){
                reflush = true;
            } else {
                DateTime comp = DateUtil.offset(record.getUpdateTime(), DateField.DAY_OF_WEEK_IN_MONTH,1);  //过了一天
                if (comp.compareTo(new Date())<1) {
                    reflush = true;
                }
            }
        } else {
            reflush = true;
        }
        if (!reflush){
            return;
        }
        Result<Object> result = heZhangController.statisticsPatrolRecord();
        List<PatrolRecordVo> records  = ( List<PatrolRecordVo>)result.getResult();
        for (PatrolRecordVo recordVo:records){
            LambdaQueryWrapper<PatrolRecord> querySaWrapper = new LambdaQueryWrapper<PatrolRecord>();
            PatrolRecord record = null;
            querySaWrapper.eq(PatrolRecord::getRegionName, recordVo.getRegionName());
            List<PatrolRecord> list = patrolRecordService.list(querySaWrapper);
            if (list.size()>0) {
                record = list.get(0);
                BeanUtil.copyProperties(recordVo,record);
                patrolRecordService.updateById(record);
            } else {
                record = new PatrolRecord();
                BeanUtil.copyProperties(recordVo,record);
                record.setId(UUIDGenerator.generate());
                patrolRecordService.save(record);
            }
        }
    }
}
